<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="openDialog"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="isLoading" :data="list">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button
                    size="small"
                    type="success"
                    @click="openAssignDialogFn(row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="editRole(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- current-page：当前页 -->
            <!-- page-sizes：下拉选择的页容量 -->
            <!-- page-size：当前页的页容量 -->
            <!-- layout：表示咱们分页的功能 -->
            <!-- total：表示的是总条数 -->
            <!-- @size-change：表示页容量发生变化 -->
            <!-- @current-change：表示页码变化 -->
            <el-pagination
              :current-page="page"
              :page-sizes="[2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyForm.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyForm.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyForm.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyForm.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog
        :title="showTitle"
        :visible="showDialog"
        :close-on-click-modal="false"
        @close="closeDialog"
      >
        <el-form
          ref="roleForm"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmAddRole">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        :close-on-click-modal="false"
        @open="getPermissionList"
        @close="closeAssignDialog"
      >
        <el-tree
          ref="tree"
          v-loading="isTreeLoading"
          :data="permissionList"
          :props="{ label: 'name' }"
          show-checkbox
          :check-strictly="true"
          default-expand-all
          node-key="id"
        />
        <template #footer>
          <div style="text-align: right">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="confirmAssignPerm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getRoleListApi,
  delRoleApi,
  addRoleApi,
  getRoleDetailByIDApi,
  editRoleApi,
  assignPermissionApi
} from '@/api/setting'
import { getCompanyInfoApi } from '@/api/company'
import { getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1,
      pagesize: 2,
      list: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不可为空', trigger: 'blur' }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      roleId: '',
      permissionList: [],
      permIdList: [],
      isTreeLoading: false
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async confirmAssignPerm() {
      const checkKeys = this.$refs.tree.getCheckedKeys()
      const params = {
        id: this.roleId,
        permIds: checkKeys
      }
      await assignPermissionApi(params)
      this.$message.success('恭喜！分配成功')
      this.closeAssignDialog()
    },
    /**
     * 获取权限列表
     */
    async getPermissionList() {
      const { data } = await getPermissionListApi()
      this.permissionList = transListToTreeData(data, '0')
    },
    async openAssignDialogFn(id) {
      this.isTreeLoading = true
      this.showAssignDialog = true
      this.roleId = id
      const { data: { permIds }} = await getRoleDetailByIDApi(id)
      this.permIdList = permIds
      this.$refs.tree.setCheckedKeys(this.permIdList)
      this.isTreeLoading = false
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async getCompanyInfo() {
      const companyId = this.$store.state.user.userInfo.companyId
      const { data } = await getCompanyInfoApi(companyId)
      this.companyForm = data
    },
    /**
     * 编辑回显
     */
    async editRole(id) {
      const { data } = await getRoleDetailByIDApi(id)
      this.form = data
      this.showDialog = true
    },
    /**
     * 添加
     */
    confirmAddRole() {
      this.$refs.roleForm.validate(async(flag) => {
        if (!flag) return
        if (this.form.id) {
          await editRoleApi(this.form)
          this.$message.success('恭喜！编辑成功')
        } else {
          await addRoleApi(this.form)
          this.$message.success('恭喜！添加成功')
        }
        this.closeDialog()
        this.getRoleList()
      })
    },
    /**
     * 打开弹框
     */
    openDialog() {
      this.showDialog = true
    },
    /**
     * 关闭弹框
     */
    closeDialog() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
      // this.form.description = ''
    },
    /**
     * 获取角色列表
     */
    async getRoleList() {
      this.isLoading = true
      const {
        data: { rows, total }
      } = await getRoleListApi(this.page, this.pagesize)
      this.list = rows
      this.total = total
      this.isLoading = false
    },
    /**
     * 页容量变化
     */
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.getRoleList()
    },
    /**
     * 页码变化
     */
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },
    indexMethod(index) {
      return this.pagesize * (this.page - 1) + index + 1
    },
    /**
     * 删除角色
     */
    delRole(id) {
      this.$confirm(this.$t('setting.tips'), this.$t('setting.tipsTitle'))
        .then(async() => {
          await delRoleApi(id)
          this.$message.success('删除成功！')
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.getRoleList()
        })
        .catch(() => {})
    }
  }
}
</script>

<style>
</style>
